package com.shanghaionstar.discover;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.onstar.cn.auth.userProfile.Vehicle;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.EncryptUtil;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.common.CustomLayoutsGroup;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BaseFragment;
import com.onstar.cn.mag.publicService.response.ResponBannerEntity;
import com.onstar.cn.rxconstants.RxConstants;
import com.onstar.cn.sqlite.entities.UserAddressEntity;
import com.onstar.cn.weight.discover.ItemViewData;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.DiscoverActivity;
import com.shanghaionstar.activity.webview.handler.CommonWebViewActivity;
import com.shanghaionstar.activity.webview.handler.IWebType;
import com.shanghaionstar.activity.webview.handler.ShareReportWebHandler;
import com.shanghaionstar.activity.webview.handler.WebDataEntity;
import com.shanghaionstar.carmanage.ChargingPileActivity;
import com.shanghaionstar.carmanage.chargpile.ChargingPileListFragment;
import com.shanghaionstar.dealersorder.DealersOrderActivity;
import com.shanghaionstar.discover.charge.ChargeModeFragment;
import com.shanghaionstar.discover.geofence.GeofenceHomeActivity;
import com.shanghaionstar.discover.iview.IDiscoverView;
import com.shanghaionstar.discover.presenter.DiscoverFragmentPresenter;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.home.ImageCycleView;
import com.shanghaionstar.iview.ILoginListener;
import com.shanghaionstar.login.register.JoinMeUtils;
import com.shanghaionstar.nav.NavActivity;
import com.shanghaionstar.smart.SmartHomeActivity;
import com.shanghaionstar.smart.zxing.MipcaActivityCapture;
import com.shanghaionstar.sqlite.UserAddressInfoImpl;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.JoinMeConstants;
import com.shanghaionstar.utils.LoginUtil;
import com.shanghaionstar.weight.DiscoverItemLayout;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


/**
 * Created by 6335yz on 2016/6/21.
 * 发现界面
 */
public class DiscoverFragment extends BaseFragment implements IDiscoverView, ILoginListener, CustomLayoutsGroup.OnViewItemClickListener {

    @FindViewById
    private LinearLayout datas_layout;
    @FindViewById
    private ImageCycleView discover_banner_iv;
    @FindViewById
    private LinearLayout thirds_layout;

    private ProgressDialog progress_dialog;
    private DiscoverFragmentPresenter presenter;
    private boolean isOwner;
    private LogManager logManager;


    WebDataEntity entity;

    @Override
    public int getLayoutId() {
        return R.layout.tab_fragment_discover;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        logManager = LogManager.getInstance();
        if (isFirstLoad()) {
            //  showDatas();
            presenter = new DiscoverFragmentPresenter(((BaseActivity) getActivity()).getScheduler());
            presenter.setView(this);
            presenter.commandData();
//            discover_banner_iv.commandDataDiscover();
            new LoginUtil().registLoginResult(this);
        }
        showDatas();
    }

    Bundle bundle;

    public void setArgument(Bundle bundle) {
        this.bundle = bundle;
    }

    private void dispatchPartnerEvent() {
        if (bundle != null) {
            String share3RDFlag = bundle.getString(Constants.PARTNER_3RD_FLAG);
            if (!CommonUtil.isNull(share3RDFlag) && share3RDFlag.equalsIgnoreCase(OVDEmailFragment.class.getSimpleName())) {
//                ItemViewData itemView = new ItemViewData();
//                itemView.setIcon(R.drawable.discover_vehicle_ovd);
//                itemView.setText(getString(R.string.assistant_ovdreport));
//                itemView.setClassName(DiscoverActivity.class.getName());
//                Bundle ovdBundle = new Bundle();
//                ovdBundle.putString(FinalConstants.JUMP_FLAG, OVDEmailFragment.class.getName());
//                itemView.setBundle(ovdBundle);
//                itemView.setFunctionValue(FunctionNameFindId.Find_Diagnostics.getStringValue());
//
//                onViewItemClick(itemView);
                if (itemLayout != null) {
                    itemLayout.performClickByEventTag(getString(R.string.assistant_ovdreport));
                }
                bundle.remove(Constants.PARTNER_3RD_FLAG);
            }
        }
    }

    public void performClick(String share3RDFlag) {
        LogManager.getInstance().d("share3RDFlag " + OVDEmailFragment.class.getName());
//        if (!CommonUtil.isNull(share3RDFlag) && share3RDFlag.equalsIgnoreCase(OVDEmailFragment.class.getSimpleName())) {
//            ItemViewData itemView = new ItemViewData();
//            itemView.setIcon(R.drawable.discover_vehicle_ovd);
//           // itemView.setText(getString(R.string.assistant_ovdreport));
//            itemView.setClassName(DiscoverActivity.class.getName());
//            Bundle ovdBundle = new Bundle();
//            ovdBundle.putString(FinalConstants.JUMP_FLAG, OVDEmailFragment.class.getName());
//            itemView.setBundle(ovdBundle);
//            itemView.setFunctionValue(FunctionNameFindId.Find_Diagnostics.getStringValue());
//
//            onViewItemClick(itemView);
//        }
    }

    @Override
    public void onLogin(Bundle bundle, String resultCode) {
        showDatas();
    }

    @Override
    public void onResume() {
        super.onResume();
        dispatchPartnerEvent();
        /**
         * 登录成功后如果绑定车辆是gen10则去除充电管理
         */
//        if (ApplicationUtil.getInstance().isLogin()) {
//            if (ApplicationUtil.getInstance().isGen10()) {
//                itemLayout.removeData(getString(R.string.discover_vehicle_charging));
//            }
//        }

    }

    DiscoverItemLayout itemLayout;

    private void showDatas() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                final List<ItemViewData> itemViewDatas = setupItemList();
                final List<ItemViewData> itemThirdViews = new ArrayList<>();


                boolean isLogin = ApplicationUtil.getInstance().isLogin();
                if (isLogin && ApplicationUtil.getInstance().getLoginRole() != null &&
                        ApplicationUtil.getInstance().getLoginRole().equalsIgnoreCase(JoinMeConstants.OWNER)) {
                    itemThirdViews.clear();
                    ItemViewData itemView = new ItemViewData();
                    itemView.setIcon(R.drawable.discover_scan);
                    itemView.setText(getString(R.string.function_scan));
                    itemView.setClassName(MipcaActivityCapture.class.getName());

                    Bundle scanBundle = new Bundle();
                    scanBundle.putString("title", getString(R.string.function_scan));//FinalConstants.JUMP_FLAG,
                    itemView.setBundle(scanBundle);
                    itemThirdViews.add(itemView);
                }
//                ItemViewData itemThirdView = new ItemViewData();
//                itemThirdView.setIcon(R.drawable.discover_vehicle_violation);
//                itemThirdView.setText(getString(R.string.discover_vehicle_violation));
//                itemThirdView.setClassName(DiscoverActivity.class.getName());
//                Bundle aboutBundle = new Bundle();
//                aboutBundle.putString(FinalConstants.JUMP_FLAG, VehicleViolationActivity.class.getName());
//                itemThirdView.setBundle(aboutBundle);
//                itemThirdView.setFunctionValue(FunctionNameFindId.Find_Violationcheck.getStringValue());
////                itemThirdViews.add(itemThirdView);
//                onRefresh(itemThirdViews);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showDataView(itemViewDatas);
                        showThirdView(itemThirdViews);
                    }
                });
            }
        }).start();



   /*     if(!isOwner){
            thirds_layout.setVisibility(View.GONE);
        }else{
            thirds_layout.setVisibility(View.VISIBLE);
        }*/
    }

    private List<ItemViewData> setupItemList() {
        List<ItemViewData> itemViews = new ArrayList<>();
        itemViews.clear();

        ItemViewData itemView = new ItemViewData();
        itemView.setIcon(R.drawable.charge_station);
        itemView.setText(getString(R.string.chariging_station));
        itemView.setClassName(ChargingPileActivity.class.getName());
        Bundle chargeStationBundle = new Bundle();
        chargeStationBundle.putString(FinalConstants.JUMP_FLAG, ChargingPileListFragment.class.getName());
        itemView.setBundle(chargeStationBundle);
        itemViews.add(itemView);

        itemView = new ItemViewData();
        itemView.setIcon(R.drawable.discover_vehicle_wifi);
        itemView.setText(getString(R.string.wifi_manage));
        itemView.setClassName(DiscoverActivity.class.getName());
//        itemView.setTextColor(R.color.onstar_discover_item_text_color);
//        itemView.setTextSize(15);
        Bundle wifitBundle = new Bundle();
        wifitBundle.putString(FinalConstants.JUMP_FLAG, WifiHomeFragment.class.getName());
        itemView.setBundle(wifitBundle);
        itemView.setFunctionValue(FunctionNameFindId.Find_VehicularWiFi.getStringValue());
        itemViews.add(itemView);

        itemView = new ItemViewData();
        itemView.setIcon(R.drawable.discover_vehicle_geofenceing);
        itemView.setText(getString(R.string.geofence_title));
        itemView.setClassName(DiscoverActivity.class.getName());

        Bundle geofenceBundle = new Bundle();
        geofenceBundle.putString(FinalConstants.JUMP_FLAG, GeofenceHomeActivity.class.getName());
        itemView.setBundle(geofenceBundle);
        itemView.setFunctionValue(FunctionNameFindId.Find_SecurityZone.getStringValue());
        itemViews.add(itemView);

        itemView = new ItemViewData();
        itemView.setIcon(R.drawable.discover_vehicle_smarthome);
        itemView.setText(getString(R.string.smart_home));
        itemView.setClassName(DiscoverActivity.class.getName());

        Bundle smartBundle = new Bundle();
        smartBundle.putString(FinalConstants.JUMP_FLAG, SmartHomeActivity.class.getName());
        itemView.setBundle(smartBundle);
        itemView.setFunctionValue(FunctionNameFindId.Find_Smarthome.getStringValue());
        itemViews.add(itemView);

        itemView = new ItemViewData();
        itemView.setIcon(R.drawable.discover_vehicle_charging);
        itemView.setText(getString(R.string.discover_vehicle_charging));
        itemView.setClassName(DiscoverActivity.class.getName());

        Bundle chargeBundle = new Bundle();
        chargeBundle.putString(FinalConstants.JUMP_FLAG, ChargeModeFragment.class.getName());
        itemView.setBundle(chargeBundle);
        itemView.setFunctionValue(FunctionNameFindId.Find_ChargeManagment.getStringValue());
        itemViews.add(itemView);

        itemView = new ItemViewData();
        itemView.setIcon(R.drawable.discover_vehicle_ovd);
        itemView.setText(getString(R.string.assistant_ovdreport));
        itemView.setClassName(DiscoverActivity.class.getName());

        Bundle ovdBundle = new Bundle();
        ovdBundle.putString(FinalConstants.JUMP_FLAG, OVDEmailFragment.class.getName());
        itemView.setBundle(ovdBundle);
        itemView.setFunctionValue(FunctionNameFindId.Find_Diagnostics.getStringValue());
        itemViews.add(itemView);


        itemView = new ItemViewData();
        itemView.setIcon(R.drawable.discover_vehile_dealer);
        itemView.setText(getString(R.string.function_dealer_booking));
        itemView.setClassName(DiscoverActivity.class.getName());

        Bundle dealersBundle = new Bundle();
        dealersBundle.putString(FinalConstants.JUMP_FLAG, DealersOrderActivity.class.getName());
        itemView.setBundle(dealersBundle);
        itemView.setFunctionValue(FunctionNameFindId.Find_DealerReservation.getStringValue());
        itemViews.add(itemView);

        itemView = new ItemViewData();
        itemView.setIcon(R.drawable.discover_vehile_assessment);
        itemView.setText(getString(R.string.discover_vehicle_assessment));
        itemView.setClassName(CommonWebViewActivity.class.getName());

        Bundle assessmentBundle = new Bundle();
        assessmentBundle.putString("className", com.shanghaionstar.activity.webview.handler.CommonWebViewActivity.class.getName());
        entity = new WebDataEntity();
        entity.setLinkUrl(Constants.CURRENT_PREFIX_H5_URL + Constants.CAR_ASSESSMENT);
        entity.setTopTitle(getString(R.string.driver_assessment_title));
        entity.setCanGoBack(true);
        entity.setWhat(IWebType.TYPE_SHARE_REPORT);
        entity.setClzName(ShareReportWebHandler.class.getName());
        assessmentBundle.putParcelable(IWebType.KEY_WEB_DATA, entity);

//        assessmentBundle.putString("linkUrl", EncryptUtil.decryptBase64(baseActivity, Constants.PREFIX_H5_URL) + Constants.CAR_ASSESSMENT);
//        assessmentBundle.putString("topTitle", getString(R.string.driver_assessment_title));
//        assessmentBundle.putBoolean("canGoBack", true);
        itemView.setBundle(assessmentBundle);
        itemView.setFunctionValue(FunctionNameFindId.Find_CarAssessment.getStringValue());
        itemViews.add(itemView);


        itemView = new ItemViewData();
        itemView.setIcon(R.drawable.discover_vehicle_callus);
        itemView.setText(getString(R.string.assistant_connect));
        itemView.setFunctionValue(FunctionNameFindId.Find_CallUs.getStringValue());
        itemViews.add(itemView);

        itemView = new ItemViewData();
        itemView.setIcon(R.drawable.discover_vehicle_home);
        itemView.setText(getString(R.string.function_go_home));
        itemView.setClassName(NavActivity.class.getName());

        Bundle homeAddrBundle = new Bundle();
        homeAddrBundle.putString("title", getString(R.string.function_go_home));//FinalConstants.JUMP_FLAG,
        itemView.setBundle(homeAddrBundle);
        itemView.setFunctionValue(FunctionNameFindId.Find_ToHome.getStringValue());
        itemViews.add(itemView);

        itemView = new ItemViewData();
        itemView.setIcon(R.drawable.discover_vehicle_company);
        itemView.setText(getString(R.string.function_go_company));
        itemView.setClassName(NavActivity.class.getName());

        Bundle compAddrBundle = new Bundle();
        compAddrBundle.putString("title", getString(R.string.function_go_company));//FinalConstants.JUMP_FLAG,
        itemView.setBundle(compAddrBundle);
        itemView.setFunctionValue(FunctionNameFindId.Find_ToOffice.getStringValue());
        itemViews.add(itemView);


//

//        itemView = new ItemViewData();
//        itemView.setIcon(R.drawable.discover_vehicle_illegal);
//        itemView.setText(getString(R.string.discover_vehicle_illegal));
//        itemViews.add(itemView);

        onRefresh(itemViews);
        return itemViews;
    }

    public void addBrandItemViewData(List<ItemViewData> itemViews) {
        ItemViewData itemView = new ItemViewData();
        itemView.setIcon(isChevrolet() ? R.drawable.discover_cherovlet_club : R.drawable.discover_brand_club);
        itemView.setText(getString(R.string.sc_brand_club));
        itemView.setClassName(CommonWebViewActivity.class.getName());

        Bundle brandBundle = new Bundle();
        brandBundle.putString("title", getString(R.string.sc_brand_club));//FinalConstants.JUMP_FLAG,
        itemView.setBundle(brandBundle);
        itemView.setFunctionValue(FunctionNameFindId.Find_Club.getStringValue());
        itemViews.add(itemView);
    }

    private void showDataView(List<ItemViewData> itemViews) {
        if (itemLayout == null) {
            itemLayout = new DiscoverItemLayout(getActivity());
        }
        itemLayout.setOnViewItemClickListener(this);
        itemLayout.showDatas(itemViews, getString(R.string.discover_onstar_service));
        datas_layout.removeAllViews();
        datas_layout.addView(itemLayout);
    }

    private void showThirdView(List<ItemViewData> itemViews) {
        DiscoverItemLayout itemThirdLayout = new DiscoverItemLayout(getActivity());
        itemThirdLayout.setOnViewItemClickListener(this);
        itemThirdLayout.showDatas(itemViews, getString(R.string.discover_onstar_third_service));
        thirds_layout.removeAllViews();
        thirds_layout.addView(itemThirdLayout);
    }

    public void removeItem(List<ItemViewData> itemViews, String itemTitle) {
        Iterator<ItemViewData> it = itemViews.iterator();
        while (it.hasNext()) {
            ItemViewData itemView = it.next();
            if (itemView.getText().equalsIgnoreCase(itemTitle)) {
                it.remove();
                break;
            }
        }
    }

    public boolean isCadillac() {
        Vehicle vehicle = ApplicationUtil.getInstance().getCurrentVehicle();
        if (vehicle == null)
            return false;
        String desc = vehicle.getModelDesc();
        return desc != null && (desc.contains("凯迪拉克") || desc.toLowerCase().contains("Cadillac".toLowerCase()));
    }

    public boolean isAvailableBrand() {
        return isCadillac() || isChevrolet();
    }

    public boolean isChevrolet() {
//        (desc.contains("雪佛兰") || desc.toLowerCase().contains("Chevrolet".toLowerCase()))
        Vehicle vehicle = ApplicationUtil.getInstance().getCurrentVehicle();
        if (vehicle == null)
            return false;
        String desc = vehicle.getModelDesc();
        return desc != null && (desc.contains("雪佛兰") || desc.toLowerCase().contains("Chevrolet".toLowerCase()));
    }

    public void onRefresh(List<ItemViewData> itemViews) {
        boolean isLogin = ApplicationUtil.getInstance().isLogin();
        if (!isLogin) {
            return;
        }
        String loginRole = ApplicationUtil.getInstance().getLoginRole();
        boolean isNull = CommonUtil.isNull(loginRole);
        boolean isVisitor = !isNull & loginRole.equalsIgnoreCase(JoinMeConstants.VISITOR);
        if (isVisitor) {
//            removeItem(itemViews, getString(R.string.chariging_station));
            return;
        }
        isOwner = loginRole.equalsIgnoreCase(JoinMeConstants.OWNER);

        logManager.d("isOwner" + isOwner);
        boolean isGen10 = ApplicationUtil.getInstance().isGen10();

        logManager.d("isGen10" + isGen10);
        boolean isPhev = ApplicationUtil.getInstance().isPhev();

        logManager.d("isPhev" + isPhev);
        if (!isPhev) {
            removeItem(itemViews, getString(R.string.chariging_station));
        }
        //GEN10 车主 PHEV
        if (isGen10 && isOwner && isPhev) {
            if (isAvailableBrand()) {
                addBrandItemViewData(itemViews);
            }
            return;
        }
        if (isGen10 && isOwner && !isPhev) {
//            itemLayout.removeData(getString(R.string.discover_vehicle_charging));
            removeItem(itemViews, getString(R.string.discover_vehicle_charging));
            if (isAvailableBrand()) {
                addBrandItemViewData(itemViews);
            }
            return;
        }
        if (isGen10 && !isOwner && isPhev) {
            removeItem(itemViews, getString(R.string.geofence_title));
//            itemLayout.removeData(getString(R.string.geofence_title));
            removeItem(itemViews, getString(R.string.discover_vehicle_violation));
            removeItem(itemViews, getString(R.string.function_dealer_booking));
            removeItem(itemViews, getString(R.string.smart_home));
            return;
        }
        if (isGen10 && !isOwner && !isPhev) {
            removeItem(itemViews, getString(R.string.geofence_title));
            removeItem(itemViews, getString(R.string.discover_vehicle_charging));
            removeItem(itemViews, getString(R.string.discover_vehicle_violation));
            removeItem(itemViews, getString(R.string.function_dealer_booking));
            removeItem(itemViews, getString(R.string.smart_home));

//            itemLayout.removeData(getString(R.string.geofence_title));
//            itemLayout.removeData(getString(R.string.smart_home));
//            itemLayout.removeData(getString(R.string.discover_vehicle_charging));
            return;
        }
        if (!isGen10 && isOwner && isPhev) {
            removeItem(itemViews, getString(R.string.geofence_title));
            removeItem(itemViews, getString(R.string.wifi_manage));
            removeItem(itemViews, getString(R.string.smart_home));
//            itemLayout.removeData(getString(R.string.geofence_title));
//            itemLayout.removeData(getString(R.string.smart_home));
//            itemLayout.removeData(getString(R.string.wifi_manage));
            if (isAvailableBrand()) {
                addBrandItemViewData(itemViews);
            }
            return;
        }
        if (!isGen10 && isOwner && !isPhev) {
            removeItem(itemViews, getString(R.string.geofence_title));
            removeItem(itemViews, getString(R.string.wifi_manage));
            removeItem(itemViews, getString(R.string.discover_vehicle_charging));
            removeItem(itemViews, getString(R.string.smart_home));
//            itemLayout.removeData(getString(R.string.geofence_title));
//            itemLayout.removeData(getString(R.string.smart_home));
//            itemLayout.removeData(getString(R.string.wifi_manage));
//            itemLayout.removeData(getString(R.string.discover_vehicle_charging));
            if (isAvailableBrand()) {
                addBrandItemViewData(itemViews);
            }
            return;
        }
        if (!isGen10 && !isOwner && isPhev) {
            removeItem(itemViews, getString(R.string.geofence_title));
            removeItem(itemViews, getString(R.string.wifi_manage));

            removeItem(itemViews, getString(R.string.discover_vehicle_violation));
            removeItem(itemViews, getString(R.string.smart_home));
//            itemLayout.removeData(getString(R.string.geofence_title));
//            itemLayout.removeData(getString(R.string.smart_home));
//            itemLayout.removeData(getString(R.string.wifi_manage));
            removeItem(itemViews, getString(R.string.discover_vehicle_violation));
            removeItem(itemViews, getString(R.string.function_dealer_booking));
            return;
        }
        if (!isGen10 && !isOwner && !isPhev) {
            removeItem(itemViews, getString(R.string.geofence_title));
            removeItem(itemViews, getString(R.string.wifi_manage));
            removeItem(itemViews, getString(R.string.discover_vehicle_charging));

            removeItem(itemViews, getString(R.string.discover_vehicle_violation));
            removeItem(itemViews, getString(R.string.smart_home));
//            itemLayout.removeData(getString(R.string.geofence_title));
//            itemLayout.removeData(getString(R.string.smart_home));
//            itemLayout.removeData(getString(R.string.wifi_manage));
//            itemLayout.removeData(getString(R.string.discover_vehicle_charging));
            removeItem(itemViews, getString(R.string.discover_vehicle_violation));
            removeItem(itemViews, getString(R.string.function_dealer_booking));
            return;
        }
    }


    @Override
    public boolean onViewItemClick(ItemViewData item) {
        if (item.getText().equalsIgnoreCase(getString(R.string.discover_vehicle_assessment))) {
            if (ApplicationUtil.getInstance().isLogin()) {
                //判断是不是访客
                String loginRole = ApplicationUtil.getInstance().getLoginRole();
                if (loginRole.equalsIgnoreCase(JoinMeConstants.VISITOR)) {
                    CommonWebViewActivity.launchCommonWeb(getActivity(), entity);
                }else{
                    CommonWebViewActivity.launchCommonWeb(getActivity(), entity);
                }
            } else {
                CommonWebViewActivity.launchCommonWeb(getActivity(), entity);
            }
            return false;
        } else {
            String functionValue = item.getFunctionValue();
            if (!TextUtils.isEmpty(functionValue) && !functionValue.equalsIgnoreCase(FunctionNameFindId.UnSend.getStringValue())) {
                BusinessUtil.sendReportByClickType(getActivity(), functionValue);
            }
            String funcTitle = item.getText();
//        if(funcTitle.equalsIgnoreCase(getString(R.string.smart_home))){
////            if(ApplicationUtil.isExpiredSubscriber())
//        }

            if (getString(R.string.sc_brand_club).equals(funcTitle)) {
                WebDataEntity entity = new WebDataEntity();
                String url = EncryptUtil.decryptBase64(getActivity(), Constants.CADILLAC_CLUB_URL);
                entity.setLinkUrl(isChevrolet() ? Constants.CHEVROLET_CLUB_URL : url);
                entity.setTopTitle(funcTitle);
                entity.what = IWebType.TYPE_NORMAL;
                CommonWebViewActivity.launchCommonWeb(getActivity(), entity);
                return false;
            }

            if (item.getText().equalsIgnoreCase(getString(R.string.assistant_connect))) {
                AlertDialogUtil.showAlertDialog(getActivity(), getString(R.string.dialog_warning), getString(R.string.connect_phone), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        requestRunTimePermissions(new String[]{Manifest.permission.CALL_PHONE}, new PermissionCall() {
                            @Override
                            public void requestSuccess() {
                                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + getString(R.string.connect_phone)));
                                startActivity(intent);
                            }

                            @Override
                            public void refused() {

                            }
                        });

                    }
                }, true);
                return false;
            }

            if (!ApplicationUtil.getInstance().isLogin()) {
                new LoginUtil().loginAndActionCallBack(getActivity(), RxConstants.DISCOVER_PAGE, DiscoverFragment.this, item.getBundle());
                return false;
            }
            if (ApplicationUtil.getInstance().isLogin() && ApplicationUtil.getInstance().getLoginRole().equalsIgnoreCase(Constants.VISITOR)) {
                showUpgradeDia();
                return false;
            }

            if (ApplicationUtil.getInstance().isLogin()) {
                if (funcTitle.equalsIgnoreCase(getString(R.string.ele_fence))) {
                    if (BusinessUtil.isVisitor(getContext()))
                        return false;
                    if (!BusinessUtil.checkPackageRight(Constants.ENTITLEMENT_M08SAFETY_ZONE, getActivity(), true)) {
                        return false;
                    }
                }
            }

            if (getString(R.string.function_go_company).equalsIgnoreCase(funcTitle)) {
                if (checkAddr("2", funcTitle)) return false;
            } else if (getString(R.string.function_go_home).equalsIgnoreCase(funcTitle)) {
                if (checkAddr("1", funcTitle)) return false;
            }
            return true;
        }
    }

    private boolean isContainType(List<UserAddressEntity> list, String type) {
        for (UserAddressEntity entity : list) {
            String cate = entity.getCustomerCatetory();
            String userId = entity.getUserId();
            if (cate.equalsIgnoreCase(type) && ApplicationUtil.getInstance().getIdpID().equals(userId)) {
                return true;
            }
        }
        return false;
    }

    private boolean checkAddr(String cate, String title) {
        UserAddressInfoImpl mUserAddressInfoImpl = new UserAddressInfoImpl(baseActivity);
        List<UserAddressEntity> list = mUserAddressInfoImpl.getAll();
        if (list == null || list.size() == 0 || !isContainType(list, cate)) {
            Bundle bundle = new Bundle();
            bundle.putString("title", title);
            showGoHomeOrCompanyDialog(title, bundle);
            return true;
        }
        return false;
    }

    private void showGoHomeOrCompanyDialog(final String msg, final Bundle bundle) {
        AlertDialogUtil.showAlertDialog(baseActivity, getString(R.string.dialog_warning),
                getString(R.string.nav_home_comp_set, msg), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            BusinessUtil.jumpActivity(bundle, DiscoverFragment.this, NavActivity.class);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
    }


    /**
     * 升级为车主
     */
    private void showUpgradeDia() {
        AlertDialogUtil.showAlertDialog(getActivity(), R.string.dialog_warning, R.string.SB021_MSG013,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        JoinMeUtils.checkVisitor(DiscoverFragment.this);
                    }
                }, true, R.string.upgrade_to_owner);
    }

    @Override
    public void setLoading(boolean isLoading) {
        if (progress_dialog != null) {
            if (isLoading) {
                if (!progress_dialog.isShowing()) progress_dialog.show();
            } else {
                if (progress_dialog.isShowing())
                    progress_dialog.dismiss();
            }
        }
    }

    @Override
    public void onResponseError(OnStarException e) {
        discover_banner_iv.setVisibility(View.GONE);
        if (e != null)
            AlertDialogUtil.showDialogByOnstarException(getActivity(), e);
    }

    @Override
    public void onReponseSuccess(Class<?> object) {

    }


    @Override
    public Activity onActivity() {
        return getActivity();
    }

    @Override
    public void onGetBanner(List<ResponBannerEntity> entities) {
        if (CommonUtil.isNull(entities)) {
//           discover_banner_iv.initBanner();
        } else {
            final DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.drawable.home_banner_failed)
                    .showImageForEmptyUri(R.drawable.home_banner_failed).showImageOnFail(R.drawable.home_banner_failed)
                    .resetViewBeforeLoading(true).cacheInMemory(true).cacheOnDisc(false).imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
                    .bitmapConfig(Bitmap.Config.RGB_565).displayer(new FadeInBitmapDisplayer(100)).build();
            discover_banner_iv.setVisibility(View.VISIBLE);
            discover_banner_iv.setImageResources(entities, new ImageCycleView.ImageCycleViewListener() {
                @Override
                public void displayImage(Object o, ImageView imageView) {
                    if (o == null || imageView == null) {
                        discover_banner_iv.setVisibility(View.GONE);
                        return;
                    }
                    ResponBannerEntity entity = (ResponBannerEntity) o;
                    ImageLoader.getInstance().displayImage(entity.getImgUrl(), imageView, options);
                }

                @Override
                public void onImageClick(Object o, int position, View imageView) {
                    if (o == null || imageView == null) {
                        discover_banner_iv.setVisibility(View.GONE);
                        return;
                    }
                    presenter.onBannerClick((ResponBannerEntity) o);
                }
            });
        }
    }
}
